<template>
  <div class="depart-tree glo-content-area">
    <Tree
      ref="tree"
      :data="treeData"
      :render="renderContent"
      @on-select-change="handleSelect"
    />

    <DepartEdit
      v-if="ifCreate"
      :parent-depart="parentDepartId"
      @close="closeCreate"
    />
    <DepartEdit
      v-if="ifUpdate"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
  </div>
</template>

<script>
import {
  mapState,
} from 'vuex'
import {
  del,
} from '@/api/depart.js'

import DepartItem from './DepartItem'
import DepartEdit from './DepartEdit'

export default {
  components: {
    DepartEdit,
  },
  data () {
    return {
      parentDepartId: '',
      ifCreate: false,
      ifUpdate: false,
      editItem: null,
    }
  },
  computed: {
    ...mapState('depart', [
      'selectedDepart',
      'list',
    ]),
    treeData () {
      if(this.list[0]&&this.list[0].departName=="新部门"){
        // console.log('this.list1',this.list)
        this.list[0].departName=this.$t('title.newDepart')
      }
      return this.generateTreeData(this.list)
    },
    selectedDepartId: {
      get () {
        return this.selectedDepart
      },
      set (val) {
        console.log('lalal======', val)
        this.$store.commit('depart/setSelected', val)
      },
    },
    btnShow () {
      return this.$store.state.btnShow
    },
  },
  watch: {
    btnShow () {
      this.getData()
      return this.$store.state.btnShow
    }
  },
  
  mounted () {
    this.getData()
  },

  methods: {
    renderContent (h, { root, node, data }) {
      return h(DepartItem, {
        props: { data },
        on: { action: (name) => this.handleAction(name, data) },
      })
    },
    handleAction (name, depart) {
      switch (name) {
        case 'create':
          this.showCreate(depart)
          break
        case 'update':
          this.showUpdate(depart)
          break
        case 'del':
          this.handleDel(depart)
          break
      }
    },
    handleSelect (arr, target) {
      // console.log(this.treeData)
      // console.log(arr)
      // console.log(arr.length)
      // console.log(arr[0].id)arr为空页面会报错
      if (arr.length == 0) return

      sessionStorage.setItem('tableId', arr[0].id)
      this.$store.state.tableId = arr[0].id
      if (arr.length === 0) {
        // !! hack代码，阻断组件本身反选
        this.$refs.tree.handleSelect(target.nodeKey)
      } else {
        this.selectedDepartId = target.id
      }
    },

    showCreate (depart) {
      this.parentDepartId = depart.id
      this.ifCreate = true
    },
    closeCreate (ifUpdated) {
      ifUpdated && this.getData()
      this.parentDepartId = ''
      this.ifCreate = false
    },

    showUpdate (item) {
      this.editItem = item
      this.ifUpdate = true
    },
    closeUpdate (ifUpdated) {
      ifUpdated && this.getData()
      this.ifUpdate = false
    },

    generateTreeData (arr) {
      // console.log('generateTreeData=============', arr)
      const result = []
      for (let i = 0; i < arr.length; i += 1) {
        const item = arr[i]
        const treeItem = {
          ...item,
          expand: true,
        }
        if (i === 0 && !this.selectedDepartId) {
          treeItem.selected = true
          this.selectedDepartId = treeItem.id
        } else if (this.selectedDepartId === treeItem.id) {
          treeItem.selected = true
        }
        if (item.children && item.children.length) {
          treeItem.children = this.generateTreeData(item.children)
        }
        result.push(treeItem)
      }
      return result.sort((prev, next) => {
        const pervOrder = prev.departOrder || 0
        const nextOrder = next.departOrder || 0
        return pervOrder - nextOrder
      })
    },
    async getData () {
      this.$store.dispatch('depart/getList')
      // console.log(this.$store.dispatch('depart/getList'))
    },
    async handleDel (item) {
      this.$Modal.confirm({
        title: this.$t('staffIndex.staffDelDepartment'),
        // content: this.$t('devicesIndex.devStrdelIsUre') + item.departName + this.$t('staffIndex.staffDelDepartmentIs'),
        content: this.$t('staffIndex.staffDelDepartmentIs'),
        onOk: async () => {
          const { success } = await del({ id: item.id })
          if (success) {
            this.$Message.success(this.$t('versionIndex.verDelBtnSucc'))
            this.getData()
          } else {
            this.$Message.error(this.$t('devicesIndex.devdevStrDelEquipmentfailedBind'))
          }
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
.depart-tree {
  float: left;
  // width: 300px;
  width: 30%;
  max-width: 300px;
  margin-right: @padding-hov;
  min-height: 500px;

  /deep/ .ivu-tree-title {
    width: 100%;
    width: calc(100% - 21px);
  }
}
</style>
